package com.ziyueyuwen.xiniao.service.baseservice.lesson.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ziyueyuwen.xiniao.bean.ZyClassInfo;
import com.ziyueyuwen.xiniao.bean.ZyClassLessonInfo;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.bean.vo.ZyClassUserVO;
import com.ziyueyuwen.xiniao.bean.vo.ZyLessonVO;
import com.ziyueyuwen.xiniao.dao.ZyClassInfoMapper;
import com.ziyueyuwen.xiniao.dao.ZyClassLessonInfoMapper;
import com.ziyueyuwen.xiniao.service.*;
import com.ziyueyuwen.xiniao.service.baseservice.lesson.ZyClassLessonService;
import com.ziyueyuwen.xiniao.util.EEOUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ziyueyuwen.xiniao.util.ConstUtil.KEY_DATA;
import static com.ziyueyuwen.xiniao.util.ConstUtil.KEY_ERRNO;

/**
 * @author wancheng  on 2019/1/22.
 */
@Service
public class ZyClassLessonServiceImpl implements ZyClassLessonService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ZyClassLessonInfoMapper zyClassLessonInfoMapper;
    @Autowired
    ZyClassInfoMapper zyClassInfoMapper;
    @Autowired
    MessageTaskTemplateService messageTaskTemplateService;
    @Autowired
    ClassUserService classUserService;
    @Autowired
    ClassService classService;
    @Autowired
    LessonService lessonService;
    @Autowired
    LessonUserService lessonUserService;
    @Autowired
    UserService userService;

    @Override
    public ZyClassLessonInfo getByPreKey(Integer lessonId) {
        return zyClassLessonInfoMapper.selectByPrimaryKey(lessonId);
    }

    @Override
    public List<ZyClassLessonInfo> getLessonByClassId(Integer classId) {
        ZyClassLessonInfo param = new ZyClassLessonInfo();
        param.setClassId(classId);
        return zyClassLessonInfoMapper.select(param);
    }

    @Override
    public List<ZyClassLessonInfo> getLessonByClassIdAndStudent(Integer classId, String studentAccount) {
        return zyClassLessonInfoMapper.getLessonForStudent(classId,studentAccount);
    }

    @Override
    public List<ZyClassLessonInfo> getTransferLesson(Integer classId, String studentAccount) {
        return zyClassLessonInfoMapper.getTransferLesson(classId,studentAccount);
    }

    @Override
    public ZyClassLessonInfo getLesson(Integer classId, Integer lessonIndex) {
        ZyClassLessonInfo param = new ZyClassLessonInfo();
        param.setClassId(classId);
        param.setLessonIndex(lessonIndex);
        return zyClassLessonInfoMapper.selectOne(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLesson(ZyClassLessonInfo lessonInfo) throws Exception {
        if (lessonInfo.getClassId() == null) {
            throw new Exception("classId为空");
        }
        ZyClassInfo classInfo = zyClassInfoMapper.selectByPrimaryKey(lessonInfo.getClassId());
        if (classInfo == null) {
            throw new Exception("班级不存在");
        }
        ZyClassUserVO teacher = classUserService.getTeacherByClassId(lessonInfo.getClassId());
        if (teacher == null) {
            throw new Exception("该班级老师不存在");
        }
        Integer maxLessonIndex = zyClassLessonInfoMapper.getMaxLessonIndex(lessonInfo.getClassId());
        //课节的lessonIndex
        lessonInfo.setLessonIndex(maxLessonIndex + 1);
        //课节名称
        lessonInfo.setClassLessonName(classInfo.getClassName() + "-" + lessonInfo.getLessonIndex());
        //同步eeo
        Integer eeoLessonId = EEOUtil.addCourseClass(lessonInfo, classInfo.getEeoCourseId(), teacher.getUserAccount(), teacher.getUserName());
        //查询最大 lessonIndex
        lessonInfo.setClassId(classInfo.getId());
        lessonInfo.setEeoCourseId(classInfo.getEeoCourseId());
        lessonInfo.setEeoLessonId(eeoLessonId);
        //保存返回主键
        zyClassLessonInfoMapper.insertUseGeneratedKeys(lessonInfo);
        //生产当前课节 消息任务模板
        messageTaskTemplateService.insertLessonTask(lessonInfo);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ZyClassLessonInfo> saveLessonBatch(List<ZyClassLessonInfo> lessonInfos, Integer classId, String teacherAccount, Integer seatNum) throws Exception {
        ZyClassInfo classInfo = zyClassInfoMapper.selectByPrimaryKey(classId);
        ZyUser teacher = userService.getByAccount(teacherAccount);
        List<ZyUser> students = userService.getStudents(classId);
        for (ZyUser s: students) {
            if (s.getUserAccount().equals(teacherAccount)){
                throw new Exception("老师和学生不能为同一个人");
            }
        }
        //同步eeo
        JSONArray res = EEOUtil.addCourseClassMultiple(lessonInfos, classInfo.getEeoCourseId(), teacherAccount, teacher.getUserName(), seatNum);
        List<ZyClassLessonInfo> eeoSyncSuccess = new ArrayList<>();
        List<ZyClassLessonInfo> eeoSyncError = new ArrayList<>();
        for (int i = 0; i < lessonInfos.size(); i++) {
            logger.info("EEO批量返回数据,index={},json={}", i, res.getString(i));
            ZyClassLessonInfo current = lessonInfos.get(i);
            Integer errno = res.getJSONObject(i).getIntValue(KEY_ERRNO);
            Integer data = res.getJSONObject(i).getIntValue(KEY_DATA);
            if (errno == 1) {
                current.setEeoLessonId(data);
                current.setSyncResult(true);
                current.setLessonIndex(i + 1);
                eeoSyncSuccess.add(current);
            } else {
                current.setEeoLessonId(0);
                current.setSyncResult(false);
                eeoSyncError.add(current);
            }
        }
        if (CollectionUtils.isNotEmpty(eeoSyncSuccess)){
            //保存至数据库
            zyClassLessonInfoMapper.insertList(eeoSyncSuccess);
            logger.info("保存课节成功,lesson={}", JSON.toJSON(eeoSyncSuccess));
        }

        //修改课节排序
        lessonService.arrangeClassLesson(classId);
        //生产模板消息
        messageTaskTemplateService.insertLessonTaskBatch(eeoSyncSuccess);
        //添加lesson-user数据
        lessonUserService.insertBatch(classId,teacherAccount,eeoSyncSuccess);
        return eeoSyncError;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLesson(ZyClassLessonInfo update, String teacherAccount) throws Exception {
        ZyClassLessonInfo lessonInfo = lessonService.getByLessonId(update.getId());

        ZyUser teacher = userService.getByAccount(teacherAccount);
        if (teacher == null) {
            throw new Exception("不存在的老师");
        }
        ZyClassLessonInfo exist = getByPreKey(update.getId());
        update.setEeoCourseId(exist.getEeoCourseId())
                .setClassLessonName(exist.getClassLessonName())
                .setEeoLessonId(exist.getEeoLessonId());
        //修改课节数据
        zyClassLessonInfoMapper.updateByPrimaryKeySelective(update);
        //修改课节排序
        lessonService.arrangeClassLesson(lessonInfo.getClassId());
        //修改课节老师
        lessonUserService.updateTeacher(update.getId(), teacherAccount);
        //修改课节发送消息时间
        messageTaskTemplateService.updateLessonTime(update.getId(),update.getBeginTime(),update.getEndTime());
        //eeo编辑课节
        EEOUtil.editCourseClass(update, teacher.getUserAccount(), teacher.getUserName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteLesson(Integer lessonId) {
        ZyClassLessonInfo lessonInfo = zyClassLessonInfoMapper.selectByPrimaryKey(lessonId);
        zyClassLessonInfoMapper.deleteByPrimaryKey(lessonId);
        //修改课节排序
        lessonService.arrangeClassLesson(lessonInfo.getClassId());

    }

    @Override
    public Integer getMaxLessonIndex(Integer classId) {
        return zyClassLessonInfoMapper.getMaxLessonIndex(classId);
    }

    @Override
    public List<ZyLessonVO> getLessonAlreadyUsed(Integer classId) {
        return zyClassLessonInfoMapper.getLessonAlreadyUsed(classId);
    }

    @Override
    public List<ZyLessonVO> getLessonUnUsed(Integer classId) {
        return zyClassLessonInfoMapper.getLessonByClassIdAndDate(classId, new Date());
    }
}
